package jchat.genral;


import java.io.UnsupportedEncodingException;

import jchat.interfaces.IAppManager;
import jchat.services.IMService;
import jchat.types.Session;


import org.json.JSONObject;



import android.annotation.SuppressLint;
import android.app.ActionBar;
//import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import chat.jdaas.R;


public class Login extends Activity {	

    protected static final int NOT_CONNECTED_TO_SERVICE = 0;
	protected static final int FILL_BOTH_USERNAME_AND_PASSWORD = 1;
	public static final String AUTHENTICATION_FAILED = "0";
	public static final String FRIEND_LIST = "FRIEND_LIST";
	protected static final int MAKE_SURE_USERNAME_AND_PASSWORD_CORRECT = 2 ;
	protected static final int NOT_CONNECTED_TO_NETWORK = 3;
	private EditText usernameText;
    private EditText passwordText;
    private Button cancelButton;
    private String data;
    private ReadContact objcontact;
    JSONObject objjson;
    ActionBar act;
   
    String name=new String();
    String pwd=new String();
    private Session session=new Session();
	public static final String PREFS_NAME = "LoginPrefs";
    private IAppManager imService;
    public static final int SIGN_UP_ID = Menu.FIRST;
    public static final int EXIT_APP_ID = Menu.FIRST + 1;
   public String contactlist=null;
  
   SharedPreferences sh_Pref;
	Editor toEdit;
   //UserSessionManager usersession;
   //ActionBar act;
    private ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder service) {
            // This is called when the connection with the service has been
            // established, giving us the service object we can use to
            // interact with the service.  Because we have bound to a explicit
            // service that we know is running in our own process, we can
            // cast its IBinder to a concrete class and directly access it.
            imService = ((IMService.IMBinder)service).getService();  
            
            if (imService.auth == true)
            {
            	Intent i = new Intent(Login.this, FriendList.class);																
				startActivity(i);
				Login.this.finish();
				
            }
            /*if(imService.isUserLoggedIn()==true)
            {
            	Intent i = new Intent(Login.this, FriendList.class);																
				startActivity(i);
				Login.this.finish();
            }*/
        }

        public void onServiceDisconnected(ComponentName className) {
            // This is called when the connection with the service has been
            // unexpectedly disconnected -- that is, its process crashed.
            // Because it is running in our same process, we should never
            // see this happen.
        	imService = null;
            Toast.makeText(Login.this, R.string.local_service_stopped,
                    Toast.LENGTH_SHORT).show();
        }
    };
	
    
    
    /** Called when the activity is first created. */	
	
	@SuppressLint("NewApi")
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);    

        /*
         * Start and bind the  imService 
         **/
    	startService(new Intent(Login.this,  IMService.class));			
	
               
        setContentView(R.layout.login_screen);
        Bundle extras = this.getIntent().getExtras();
        
          act=getActionBar();
        session.key =extras.getString(Session.KEY);
        session.password=extras.getString(Session.PASSWORD);
        setTitle(session.key);
        //Toast.makeText(getApplicationContext(), "userlogin status"+usersession.checkLogin(), Toast.LENGTH_LONG).show();
        //act=getActionBar();
    /*     settings = getSharedPreferences(PREFS_NAME, 0);
		if (settings.getString("logged", "").toString().equals("logged"))
		{
			 Session.username=settings.getString("username", "");
			 Session.pwd=settings.getString("pwd", "");
			//name=Session.username;
			//pwd=Session.pwd;
			
			 
			
			
			
			//Intent intent = new Intent(Login.this, FriendList.class);
			//startActivity(intent);
		}*/
        
        usernameText = (EditText) findViewById(R.id.userName);
        //passwordText = (EditText) findViewById(R.id.password);        
      //  objcontact=new ReadContact(this);
	//      objjson=new JSONObject();
	     // objjson=
//	      data=objcontact.getcontects().toString();
	    //  Toast.makeText(getApplicationContext(), data, Toast.LENGTH_LONG).show();
        
        
       
        
        
    }
    
    @Override
    protected Dialog onCreateDialog(int id) 
    {    	
    	int message = -1;    	
    	switch (id) 
    	{
    		case NOT_CONNECTED_TO_SERVICE:
    			message = R.string.not_connected_to_service;			
    			break;
    		case FILL_BOTH_USERNAME_AND_PASSWORD:
    			message = R.string.fill_both_username_and_password;
    			break;
    		case MAKE_SURE_USERNAME_AND_PASSWORD_CORRECT:
    			message = R.string.make_sure_username_and_password_correct;
    			break;
    		case NOT_CONNECTED_TO_NETWORK:
    			message = R.string.not_connected_to_network;
    			break;
    		default:
    			break;
    	}
    	
    	if (message == -1) 
    	{
    		return null;
    	}
    	else 
    	{
    		return new AlertDialog.Builder(Login.this)       
    		.setMessage(message)
    		.setPositiveButton(R.string.OK, new DialogInterface.OnClickListener() {
    			public void onClick(DialogInterface dialog, int whichButton) {
    				/* User clicked OK so do some stuff */
    			}
    		})        
    		.create();
    	}
    }

	@Override
	protected void onPause() 
	{
		unbindService(mConnection);
		super.onPause();
	}

	@Override
	protected void onResume() 
	{		
		bindService(new Intent(Login.this, IMService.class), mConnection , Context.BIND_AUTO_CREATE);
	    		
		super.onResume();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main, menu);
        return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    // Handle presses on the action bar items
	    switch (item.getItemId()) {
	        case R.id.done_item:
	            //openSearch();
	        	if (imService == null) {
					Toast.makeText(getApplicationContext(),R.string.not_connected_to_service, Toast.LENGTH_LONG).show();
					//showDialog(NOT_CONNECTED_TO_SERVICE);
					
				}
				else if (imService.isNetworkConnected() == false)
				{
					Toast.makeText(getApplicationContext(),R.string.not_connected_to_network, Toast.LENGTH_LONG).show();
					//showDialog(NOT_CONNECTED_TO_NETWORK);
					
				}
				
					
					Thread loginThread = new Thread(){
						private Handler handler = new Handler();
						@SuppressWarnings("unused")
						@Override
						public void run() {
							String result = null;
							String gh=null;
							try {
								
								/*SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
								SharedPreferences.Editor editor = settings.edit();
								editor.putString("logged", "logged");
								editor.putString("username", usernameText.getText().toString());
								editor.putString("pwd", passwordText.getText().toString());
								editor.commit();*/
								
								result = imService.authenticateUser(session.key, session.password,usernameText.getText().toString());
								
						     	//gh=imService.sendcontectlist(data);6
							} catch (UnsupportedEncodingException e) {
								
								e.printStackTrace();
							}
							if (result == null || result.equals(AUTHENTICATION_FAILED)) 
							{
								/*
								 * Authenticatin failed, inform the user
								 */
								handler.post(new Runnable(){
									public void run() {	
										Toast.makeText(getApplicationContext(),R.string.make_sure_username_and_password_correct, Toast.LENGTH_LONG).show();

										//showDialog(MAKE_SURE_USERNAME_AND_PASSWORD_CORRECT);
									}									
								});
														
							}
							else {
							
								/*
								 * if result not equal to authentication failed,
								 * result is equal to friend list of the user
								 */		
								handler.post(new Runnable(){
									public void run() {		
										//contactlist=imService.sendcontectlist(data);
										
										Intent i = new Intent(Login.this, FriendList.class);												
										//i.putExtra(FRIEND_LIST, result);						
										startActivity(i);	
										Login.this.finish();
										
								       /* Intent i = new Intent(getApplicationContext(), FriendList.class);
										i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
										
										// Add new Flag to start new Activity
										i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
										startActivity(i);
										
										finish();*/
									}									
								});
								
							}
							
						}
					};
					loginThread.start();
					
				
						
		
	            return true;
	       
	        default:
	            return super.onOptionsItemSelected(item);
	    }
	}
    
   
}

